package xyz.yq56.easytool.utils.http;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * @author yiqiang
 */
@SuppressWarnings("ALL")
public class UnSafeX509TrustManager implements X509TrustManager {


    public static SSLSocketFactory sslSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
        // 创建SSLContext
        SSLContext sslContext = SSLContext.getInstance("SSL");
        TrustManager[] tm = {new UnSafeX509TrustManager()};
        // 初始化
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 获取SSLSocketFactory对象


        return sslContext.getSocketFactory();
    }

    public static TrustAnyHostnameVerifier trustAnyHostnameVerifier() {
        return new TrustAnyHostnameVerifier();
    }


    /***
     * 校验https网址是否安全
     *
     * @author solexit06
     *
     */
    public static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            // 直接返回true:默认所有https请求都是安全的
            return true;
        }
    }


    /**
     * 里面的方法都是空的，当方法为空是默认为所有的链接都为安全，也就是所有的链接都能够访问到 当然这样有一定的安全风险，可以根据实际需要写入内容
     */
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }


    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }


    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}
